package com.robert.maps.kml;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.openintents.filemanager.FileManagerActivity;
import org.openintents.filemanager.util.FileUtils;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.yozi.R;
import com.robert.maps.kml.XMLparser.GpxPoiParser;
import com.robert.maps.kml.XMLparser.KmlPoiParser;
import com.robert.maps.utils.Ut;

import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Comparator;

import java.io.*;
import com.yozi.*;

import android.app.*;
import android.os.*;
import android.util.*;
import android.widget.*;

public class PoiFileList extends ListActivity {

	List<File> files = null;
	String[] filenames = null;
	String[] filepaths = null;

	private ProgressDialog dlgWait;
	protected ExecutorService mThreadPool = Executors.newFixedThreadPool(2);
	private PoiManager mPoiManager;
	final Handler mHandler = new Handler();


	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);

		if (mPoiManager == null)
			mPoiManager = new PoiManager(this);

	
		final ProgressDialog pd = new ProgressDialog(this); 
		pd.setIndeterminate(true);
		pd.setMessage("Scanning SD card"); 
		pd.show(); 
		new Thread(new Runnable() 
		{ 
			public void run() 
			{ 
            		try
            		{
                	    File startingDirectory= new File("/sdcard/");

                	    files = FileListing.getFileListing(startingDirectory);

                        Collections.sort(files, new Comparator()
                        {
                            @Override
                            public int compare(Object o1, Object o2)
                            {
                        	return ((File) o1).getName().compareToIgnoreCase(((File) o2).getName());
                            }
                        });
            	
            			int i = 0, n = 0;
                	    for(File file : files )
                		{
            				String name = file.getName();

            				if (FileUtils.getExtension(file.getName()).equalsIgnoreCase(".kml") ||
            					FileUtils.getExtension(file.getName()).equalsIgnoreCase(".wpt") ||
            					FileUtils.getExtension(file.getName()).equalsIgnoreCase(".gpx") && name.charAt(0) != '.')
            				{
            					n++;
            				}
                		}

            			filenames = new String[n];
            			filepaths = new String[n];

                	    for(File file : files )
                		{
            				String name = file.getName();

            				if (FileUtils.getExtension(file.getName()).equalsIgnoreCase(".kml") ||
            					FileUtils.getExtension(file.getName()).equalsIgnoreCase(".wpt") ||
            					FileUtils.getExtension(file.getName()).equalsIgnoreCase(".gpx") && name.charAt(0) != '.')
            				{
            					filenames[i] = name;
            					filepaths[i] = file.getPath();
            					i++;
            				}
                		}

            		}
            		catch(Exception e)
            		{
            		}



				pd.dismiss(); 

				mHandler.post(mUpdateResults);


			} 
		}).start(); 


	}

    final Runnable mUpdateResults = new Runnable() 
    {
        public void run() 
        {
    		setListAdapter(new ArrayAdapter<String>(PoiFileList.this,
        	      android.R.layout.simple_list_item_1, filenames));

    		getListView().setTextFilterEnabled(true);
        }
    };


	@Override
	protected void onDestroy() 
	{
		mPoiManager.FreeDatabases();
		super.onDestroy();
	}

	@Override
	protected Dialog onCreateDialog(int id) 
	{
		switch (id) 
		{
    		case R.id.dialog_wait: 
    		{
    			dlgWait = new ProgressDialog(this);
    			dlgWait.setMessage("Please wait...");
    			dlgWait.setIndeterminate(true);
    			dlgWait.setCancelable(false);
    			return dlgWait;
    		}
		}
		return null;
	}



	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) 
	{
		super.onListItemClick(l, v, position, id);

		final int i = position;

		Log.d("FILELIST", filepaths[position]);

		File file = new File(filepaths[position]);

		if(!file.exists()){
			Toast.makeText(this, "No such file", Toast.LENGTH_LONG).show();
			return;
		}

		showDialog(R.id.dialog_wait);

		this.mThreadPool.execute(new Runnable() 
		{
			public void run() 
			{
				int CategoryId = 0;
				File file = new File(filepaths[i]);

				SAXParserFactory fac = SAXParserFactory.newInstance();
				SAXParser parser = null;
				try 
				{
					parser = fac.newSAXParser();
				} catch (ParserConfigurationException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SAXException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if(parser != null)
				{
					mPoiManager.beginTransaction();
					Ut.dd("Start parsing file " + file.getName());
					try {
						if(FileUtils.getExtension(file.getName()).equalsIgnoreCase(".kml"))
							parser.parse(file, new KmlPoiParser(mPoiManager, CategoryId));
						else if(FileUtils.getExtension(file.getName()).equalsIgnoreCase(".gpx"))
							parser.parse(file, new GpxPoiParser(mPoiManager, CategoryId));
						else if(FileUtils.getExtension(file.getName()).equalsIgnoreCase(".wpt"))
						{
							String converted = wpt2kml(filepaths[i]);
							File f = new File(converted);
							parser.parse(f, new KmlPoiParser(mPoiManager, CategoryId));
							f.delete();
						}	

						mPoiManager.commitTransaction();
					} catch (SAXException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						mPoiManager.rollbackTransaction();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						mPoiManager.rollbackTransaction();
					}
					Ut.dd("Pois commited");
				}

				dlgWait.dismiss();
				PoiFileList.this.finish();
			};
		});

	}

//-----------------------------------------------------------
 private static final char ESCAPE = '\\';
 private static final char QUOTE = '"';
 private static final char SEPARATOR = ',';

private String field(StringBuffer field, int begin, int end) {
     if (begin < 0) {
         return field.substring(0, end);
     } else {
         return field.substring(begin, end);
     }
 }


 private static char escape(char c) {
     switch (c) {
     case 'n':
         return '\n';
     case 't':
         return '\t';
     case 'r':
         return '\r';
     default:
         return c;
     }
 }

 private String[] parseLine(final String line) {
     int length = line.length();

     // Check here if the last character is an escape character so
     // that we don't need to check in the main loop.
     if (line.charAt(length - 1) == ESCAPE) {
         throw new IllegalArgumentException
             (": last character is an escape character\n" + line);
     }

     // The set of parsed fields.
     List result = new ArrayList();

     // The characters between seperators.
     StringBuffer buf = new StringBuffer(length);
     // Marks the begining of the field relative to buf, -1
     // indicates the beginning of buf.
     int begin = -1;
     // Marks the end of the field relative to buf.
     int end = 0;

     // Indicates whether or not we're in a quoted string.
     boolean quote = false;

     for (int i = 0; i < length; i++) {
         char c = line.charAt(i);
         if (quote) {
             switch (c) {
             case QUOTE:
                 quote = false;
                 break;
             case ESCAPE:
                 buf.append(escape(line.charAt(++i)));
                 break;
             default:
                 buf.append(c);
                 break;
             }

             end = buf.length();
         } else {
             switch (c) {
             case SEPARATOR:
                 result.add(field(buf, begin, end));
                 buf = new StringBuffer(length);
                 begin = -1;
                 end = 0;
                 break;
             case ESCAPE:
                 if (begin < 0) { begin = buf.length(); }
                 buf.append(escape(line.charAt(++i)));
                 end = buf.length();
                 break;
             case QUOTE:
                 if (begin < 0) { begin = buf.length(); }
                 quote = true;
                 end = buf.length();
                 break;
             default:
                 if (begin < 0 &&
                     !Character.isWhitespace(c)) {
                     begin = buf.length();
                 }
                 buf.append(c);
                 if (!Character.isWhitespace(c)) { end = buf.length(); }
                 break;
             }
         }
     }

     if (quote) {
         throw new IllegalArgumentException
             ("unterminated string\n" + line);
     } else {
         result.add(field(buf, begin, end));
     }

     String[] fields = new String[result.size()];
     result.toArray(fields);
     return fields;
 }

	String wpt2kml(String file)
	{
		String filename = file.replaceAll(".wpt", ".kml");
		
		System.out.println(filename);
		
		try
		{
			FileWriter fw = new FileWriter(filename);
			BufferedWriter writer = new BufferedWriter(fw);
			
			writer.write("<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" xmlns:kml=\"http://www.opengis.net/kml/2.2\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\r\n");
			writer.write("<Document>\r\n");
			writer.write("<name>points</name>\r\n");

			FileInputStream ifs = new FileInputStream(file);
		    DataInputStream ids = new DataInputStream(ifs);
	
		    BufferedReader reader = new BufferedReader(new InputStreamReader(ids));
		    String line = null;

			// OziExplorer Waypoint File Version 1.1
			reader.readLine();
			// WGS 84
			reader.readLine();
			// Reserved 2
			reader.readLine();
			// garmin
			reader.readLine();

		    while ((line = reader.readLine()) != null)   
			{
				String[] fields = parseLine(line);
				
			    writer.write("<Placemark>\r\n");

			    writer.write("<name>");

			    writer.write(fields[1]);

			    writer.write("</name>\r\n");

			    writer.write("<Point>\r\n");

			    writer.write("<coordinates>");
			    writer.write(fields[3]);
			    writer.write(",");
			    writer.write(fields[2]);
			    writer.write(",0.0");
			    writer.write("</coordinates>\r\n");

			    writer.write("</Point>\r\n");
			
			    writer.write("</Placemark>\r\n");
		    }
			writer.write("</Document>\r\n");
			writer.write("</kml>\r\n");
	
		    ids.close();
		    writer.close();		
		}
		catch(Exception e)
		{
			
		}
		
		return filename;
	}
	
//-----------------------------------------------------------

}